﻿using System;
using System.Collections;
using System.Html;
using System.Runtime.CompilerServices;
using jQueryApi;

namespace StorytellingScript
{
    [GlobalMethods]
    public static class Evolucao
    {
        public static void ConfigurarEvolucao()
        {
            jQuery.Select(".fichaTab :input").Attribute("disabled", "true");

            jQuery.Select(".LabelEvolucao").Each(new ElementIterationCallback(delegate(int index, Element element)
            {
                jQueryObject comp = jQuery.FromElement(element);
                comp.Bind("click", new jQueryEventHandler(delegate(jQueryEvent e)
                {
                    comp.FadeOut();
                    string[] id = comp.GetAttribute("id").Split('_');

                    string tipo = "";

                    switch (id[0])
                    {
                        case "0":
                            tipo = "Atributo";
                            break;
                        case "1":
                            tipo = "Habilidade";
                            break;
                    }

                    jQueryObject label = comp.Find("label");

                    jQuery.Select(string.Format("#evolucao tr[class=evolucao_{0}_{1}]:last", id[0], id[2])).Find("td:nth-child(5)").Html("");
               
                    int nivel = jQuery.Select(string.Format("#evolucao .evolucao_{0}_{1}", id[0], id[2])).Size() +
                        Int32.Parse(jQuery.Select(string.Format("#{0}", label.GetAttribute("for"))).GetValue()) + 1;

                    int custo = Int32.Parse(id[1]) * nivel;

                    jQuery.Select("#evolucao tbody").Append(string.Format(Template.EvolucaoGenerico, id[0], id[2], label.GetHtml(), tipo, Global.Pontos(nivel), custo));

                    jQueryObject gasto = jQuery.Select("#experienciaGasto");
                    gasto.Html((Int32.Parse(gasto.GetHtml()) + custo).ToString());

                    Calcular();

                    jQueryObject inputEvolucao = jQuery.Select("#inputEvolucao");

                    jQueryObject divEvolucao = inputEvolucao.Find(string.Format("#divEvolucao_{0}_{1}", id[0], id[2]));

                    if (divEvolucao.Length == 0)
                    {
                        inputEvolucao.Append(string.Format(Template.EvolucaoIncremento, id[0], id[2]));
                    }
                    else
                    {
                        jQueryObject incrementos = divEvolucao.Find("input[name=Incrementos]");
                        incrementos.Value((Int32.Parse(incrementos.GetValue()) + 1).ToString());
                    }

                    comp.FadeIn();
                }));
            }));
        }

        public static void ExcluirEvolucao(Element element)
        {
            jQueryObject tr = jQuery.FromElement(element).Parent().Parent();

            string prop = tr.GetAttribute("class");

            jQueryObject gasto = jQuery.Select("#experienciaGasto");
            gasto.Html((Int32.Parse(gasto.GetHtml()) - Int32.Parse(tr.Find("td:nth-child(4)").GetHtml())).ToString());

            Calcular();

            tr.Remove();

            jQueryObject divEvolucao = jQuery.Select("#inputEvolucao").Find(string.Format("#divEvolucao{0}", prop.Substr(prop.IndexOf('_'))));

            jQueryObject incrementos = divEvolucao.Find("input[name=Incrementos]");

            int incrementosValue = Int32.Parse(incrementos.GetValue());

            if (incrementosValue == 1)
            {
                divEvolucao.Remove();
            }
            else
            {
                incrementos.Value((incrementosValue - 1).ToString());
            }

            jQuery.Select(string.Format("#evolucao tr[class={0}]:last", prop)).Find("td:nth-child(5)")
                .Html(Template.EvolucaoExcluir);
        }

        public static void ConfigurarAutocompleteEvolucao()
        {
            string url = "";
            int tipo = Int32.Parse(jQuery.Select("#selecaoEvolucao").GetValue());

            switch (tipo)
            {
                case 2:
                    url = "/Especializacao/Autocompletar";
                    break;
                case 3:
                    url = "/Vantagem/Autocompletar";
                    break;
            }

            jQueryObject autoEvolucao = jQuery.Select("#autoEvolucao");
            autoEvolucao.Unbind("autocomplete");

            autoEvolucao.Plugin<StorytellingPlugin>().Autocomplete(new Dictionary(
                "source", new Action<object, Action<object>>(delegate(object request, Action<object> response)
                {
                    jQueryAjaxOptions options = new jQueryAjaxOptions();
                    options.Url = url;
                    options.Type = "POST";
                    options.DataType = "json";
                    options.Data = new Dictionary("nome", Script.Literal("{0}.term", request));
                    options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
                    {
                        response(jQuery.Map(data, new ObjectMapCallback(delegate(object item, string key)
                        {
                            return new Dictionary("label", Script.Literal("{0}.Nome", item), "value", Script.Literal("{0}.Id", item));
                        })));
                    });

                    jQuery.Ajax(options);
                }),
                "focus", new Func<jQueryEvent, object, bool>(delegate(jQueryEvent e, object ui)
                {
                    autoEvolucao.Value(Script.Literal("{0}.item.label", ui).ToString());
                    return false;
                }),
                "select", new Func<jQueryEvent, object, bool>(delegate(jQueryEvent e, object ui)
                {
                    int custo = 0;

                    jQueryObject tbody = jQuery.Select("#evolucao tbody");

                    int quant = jQuery.Select(string.Format("#evolucao .evolucao_{0}_{1}", tipo, Script.Literal("{0}.item.value", ui))).Size();

                    jQueryObject inputEvolucao = jQuery.Select("#inputEvolucao");

                    jQueryObject divEvolucao = inputEvolucao.Find(string.Format("#divEvolucao_{0}_{1}", tipo, Script.Literal("{0}.item.value", ui)));

                    jQueryObject gasto = jQuery.Select("#experienciaGasto");

                    switch (tipo)
                    {
                        case 2:
                            jQueryObject humanoEspecializacao = jQuery.Select(string.Format(".EspecializacoesId[value='{0}']", Script.Literal("{0}.item.value", ui)));

                            if (humanoEspecializacao.Length == 0 && quant == 0)
                            {
                                custo = 3;
                                tbody.Append(string.Format(Template.EvolucaoGenerico, "2", Script.Literal("{0}.item.value", ui), 
                                    Script.Literal("{0}.item.label", ui), "Especialização", "", custo));

                                inputEvolucao.Append(string.Format(Template.EvolucaoIncremento, "2", Script.Literal("{0}.item.value", ui)));

                                gasto.Html((Int32.Parse(gasto.GetHtml()) + custo).ToString());

                                Calcular();
                            }
                            break;
                        case 3:                            
                            int nivel = 0;

                            jQueryObject tr = jQuery.Select(string.Format("#evolucao tr[class=evolucao_3_{0}]:last", Script.Literal("{0}.item.value", ui)));

                            if (divEvolucao.Length == 0)
                            {
                                jQueryObject humanoVantagem = jQuery.Select(string.Format(".VantagensId[value='{0}']", Script.Literal("{0}.item.value", ui)));

                                if (humanoVantagem.Length != 0)
                                {
                                    nivel = Int32.Parse(humanoVantagem.Parent().Parent().Find("select[name=HumanoVantagemVantagemNivel]").GetValue());
                                }
                            }
                            else
                            {
                                nivel = Int32.Parse(tr.Find("td:nth-child(3)").Find("input").GetValue());
                            }

                            jQueryAjaxOptions options = new jQueryAjaxOptions();
                            options.Url = "/Vantagem/PegarProximoNivelDescontoVantagem";
                            options.Type = "POST";
                            options.DataType = "json";
                            options.Data = new Dictionary(
                                "id", Int32.Parse(jQuery.Select("input[name=Id]").GetValue()),
                                "idVantagem", Script.Literal("{0}.item.value", ui),
                                "nivel", nivel
                                );
                            options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
                            {
                                int nivelNovo = (int)Script.Literal("{0}.Nivel", data);  //Int32.Parse(data.ToString());

                                if (nivelNovo > nivel)
                                {
                                    tr.Find("td:nth-child(5)").Html("");

                                    for (int i = nivel + 1; i <= nivelNovo; i++)
                                    {
                                        custo += i * ((bool)Script.Literal("{0}.IsDesconto", data) ? 1 : 2);
                                    }

                                    tbody.Append(string.Format(Template.EvolucaoVantagem, Script.Literal("{0}.item.value", ui), 
                                        Script.Literal("{0}.item.label", ui), Global.Pontos(nivelNovo), nivelNovo, custo));

                                    if (divEvolucao.Length == 0)
                                    {
                                        inputEvolucao.Append(string.Format(Template.EvolucaoIncremento, "3", Script.Literal("{0}.item.value", ui)));
                                    }
                                    else
                                    {
                                        jQueryObject incrementos = divEvolucao.Find("input[name=Incrementos]");
                                        incrementos.Value((Int32.Parse(incrementos.GetValue()) + 1).ToString());
                                    }

                                    gasto.Html((Int32.Parse(gasto.GetHtml()) + custo).ToString());

                                    Calcular();
                                    autoEvolucao.Plugin<StorytellingPlugin>().Autocomplete("search");
                                }
                            });

                            jQuery.Ajax(options);
                            break;
                    }
                    return false;
                })
                ));
        }

        public static void Calcular()
        {
            jQuery.Select("#experienciaTotal").Html((Int32.Parse(jQuery.Select("#experienciaAtual").GetHtml())
                - Int32.Parse(jQuery.Select("#experienciaGasto").GetHtml())).ToString());
        }

        public static void AbrirDialogEvolucao()
        {
            jQuery.Select("#dialogEvolucao").Plugin<StorytellingPlugin>().Dialog("open");
        }
    }
}
